﻿using log4net;
using StoreProject.BLL;
using StoreProject.BLL.StackBLL;
using StoreProject.Entity.StackEntity;
using StoreProject.Forms.Base;
using StoreProject.Forms.UserControls;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace StoreProject.Forms.StackForms.Operate
{
    public partial class StackQueryForm : ConfigQueryExForm
    {
        ILog _log = LogManager.GetLogger("StackQueryForm");
        ProductBLL productBLL = new ProductBLL();
        StackLocationBLL stackLocationBLL = new StackLocationBLL();
        StackInBLL stackInBLL = new StackInBLL();
        public StackQueryForm()
        {
            InitializeComponent();
            #region  自定义组件开始
            //自定义组件实现
            var ch = new DatagridviewCheckboxHeaderCell();
            ch.OnCheckBoxClicked += new DatagridviewcheckboxHeaderEventHander(ch_OnCheckBoxClicked);
            var checkboxCol = this.uiDataGridView1.Columns[0] as DataGridViewCheckBoxColumn;
            checkboxCol.HeaderCell = ch;
            checkboxCol.HeaderCell.Value = string.Empty;
            #endregion
        }
        //去除datagridview列表头排序
        //    foreach (DataGridViewColumn item in dgv.Columns)
        //        item.SortMode = DataGridViewColumnSortMode.NotSortable;
        /// <summary>
        /// 单击事件
        /// </summary>
        private void ch_OnCheckBoxClicked(object sender, DatagridviewCheckboxHeaderEventArgs e)
        {
            //失去焦点操作
            uiDataGridView1.EndEdit();

            //Console.WriteLine(e.CheckedState.ToString());

            //选中事件操作
            if (e.CheckedState)
            {
                for (int i = 0; i < uiDataGridView1.Rows.Count; i++)
                {
                    uiDataGridView1.Rows[i].Cells[0].Value = 1;
                }
            }
            else
            {
                for (int i = 0; i < uiDataGridView1.Rows.Count; i++)
                {
                    uiDataGridView1.Rows[i].Cells[0].Value = 0;
                }
            }

        }

        private void StackQueryForm_Load(object sender, EventArgs e)
        {
            var list = productBLL.GetList().OrderByDescending(x => x.UpdateTime).ToList().Select(x => x.ProductName).ToArray();
            this.cmbProductName.Items.AddRange(list);

            var locationList = stackLocationBLL.GetList().OrderByDescending(x => x.UpdateTime).ToList().Select(x => x.StackName).ToArray();
            this.cmbStackLocation.Items.AddRange(locationList);

            uiDataGridView1.AutoGenerateColumns = false;
            this.Query();
        }
        public override void Query()
        {
            try
            {
                List<StackInEntity> data = new List<StackInEntity>();
                if (!string.IsNullOrEmpty(this.cmbProductName.Text) && !string.IsNullOrEmpty(this.cmbStackLocation.Text))
                {
                    data = stackInBLL.GetListByWhere(string.Format("ProductName like  '%{0}%' and StackLocation like  '%{1}%'", this.cmbProductName.Text, this.cmbStackLocation.Text)).ToList();
                }
                else if (!string.IsNullOrEmpty(this.cmbProductName.Text))
                {
                    data = stackInBLL.GetListByWhere(string.Format("ProductName like  '%{0}%' ", this.cmbProductName.Text)).ToList();
                }
                else if (!string.IsNullOrEmpty(this.cmbStackLocation.Text))
                {
                    data = stackInBLL.GetListByWhere(string.Format("StackLocation like  '%{0}%'", this.cmbStackLocation.Text)).ToList();
                }
                else
                {
                    data = stackInBLL.GetListEx().ToList();
                }
                if (data != null && data.Count > 0)
                {
                    this.uiDataGridView1.DataSource = data.OrderByDescending(x => x.UpdateTime).ToList(); ;
                }
                else
                {
                    uiDataGridView1.DataSource = null;
                    //cmbCustomer.DataSource = data;
                }
            }
            catch (Exception ex)
            {
                _log.Error("Query", ex);
            }
        }

        private void uiDataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            int index = uiDataGridView1.SelectedCells[0].RowIndex;
            //获取所在行
            var flag = Convert.ToInt32(uiDataGridView1.Rows[index].Cells[0].Value);
            if (flag == 0)
            {
                uiDataGridView1.Rows[index].Cells[0].Value = 1;
            }
            else if (flag == 1)
            {
                uiDataGridView1.Rows[index].Cells[0].Value = 0;
            }
        }

        private void btnSum_Click(object sender, EventArgs e)
        {
            int sum = 0;
            for (int i = 0; i < uiDataGridView1.Rows.Count; i++)
            {
                if (Convert.ToInt32(uiDataGridView1.Rows[i].Cells[0].Value) == 1)
                {
                    sum += Convert.ToInt32(uiDataGridView1.Rows[i].Cells[4].Value);
                }
            }
            MessageBox.Show("合计："+sum, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            List<StackInEntity> data = new List<StackInEntity>();
            if (!string.IsNullOrEmpty(this.cmbProductName.Text) && !string.IsNullOrEmpty(this.cmbStackLocation.Text))
            {
                data = stackInBLL.GetListByWhere(string.Format("ProductName like  '%{0}%' and StackLocation like  '%{1}%'", this.cmbProductName.Text, this.cmbStackLocation.Text)).ToList();
            }
            else if (!string.IsNullOrEmpty(this.cmbProductName.Text))
            {
                data = stackInBLL.GetListByWhere(string.Format("ProductName like  '%{0}%' ", this.cmbProductName.Text)).ToList();
            }
            else if (!string.IsNullOrEmpty(this.cmbStackLocation.Text))
            {
                data = stackInBLL.GetListByWhere(string.Format("StackLocation like  '%{0}%'", this.cmbStackLocation.Text)).ToList();
            }
            else
            {
                data = stackInBLL.GetListEx().ToList();
            }
            if (data == null || data.Count < 1)
            {
                MessageBox.Show("没有数据可导出!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "CSV files (*.csv)|*.csv";
            saveFileDialog.FilterIndex = 0;
            saveFileDialog.RestoreDirectory = true;
            saveFileDialog.CreatePrompt = true;
            saveFileDialog.FileName = null;
            saveFileDialog.Title = "保存";
            DateTime now = DateTime.Now;
            saveFileDialog.FileName = "库存数据汇总" + now.Year.ToString().PadLeft(2) + now.Month.ToString().PadLeft(2, '0') + now.Day.ToString().PadLeft(2, '0') + "-" + now.Hour.ToString().PadLeft(2, '0') + now.Minute.ToString().PadLeft(2, '0') + now.Second.ToString().PadLeft(2, '0');
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                Stream stream = saveFileDialog.OpenFile();
                StreamWriter sw = new StreamWriter(stream, System.Text.Encoding.GetEncoding(-0));
                string strLine = "";
                try
                {
                    StringBuilder datas = new StringBuilder();
                    //写出列名称-第一行
                    datas.Append("货品名称,库位,数量,时间");
                    //换行
                    sw.WriteLine(datas);
                    foreach (var item in data)
                    {
                        datas = new StringBuilder();
                        datas.Append(item.ProductName);
                        datas.Append(",");
                        datas.Append(item.StackLocation);
                        datas.Append(",");
                        datas.Append(item.ProductCount);
                        datas.Append(",");
                        datas.Append(item.CreateTime);
                        datas.Append(",");
                        //换行
                        sw.WriteLine(datas);
                    }
                    sw.Close();
                    stream.Close();
                    MessageBox.Show("数据被导出到：" + saveFileDialog.FileName.ToString(), "导出完毕", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "导出错误", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
            }
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            this.Query();
        }
    }
}
